import cv2
from utils.corut import get_limits
from PIL import Image

# 检测颜色
yellow = [0, 225, 255]
cap = cv2.VideoCapture(0)
while True:
    ret, frame = cap.read()
    hsvimg = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    lowerLimit, upperLimit = get_limits(color=yellow)
    # 调用掩码函数
    mask = cv2.inRange(hsvimg, lowerLimit, upperLimit)
    # 将opencv的numpy数组格式的掩码转换为PIL的image对象
    # 获取目标边界框
    mask_ = Image.fromarray(mask)
    # 获取掩码中白色区域的最小外接矩形边界框
    # 返回x1 y1 x2 y2 分别表示左上 右下角 如果获取中无白色 返回none
    bbox = mask_.getbbox()
    # 测试读取 边框数组
    print(bbox)
    if bbox is not None:
        # 解析边界框的坐标
        x1, y1, x2, y2 = bbox

        # 在原始的绘制针上标记目标 矩形
        frame = cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 5)
    cv2.imshow('frame', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()
